package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.BaseException;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    DishMapper dishMapper;
    @Autowired
    DishFlavorMapper dishFlavorMapper;
    @Autowired
    SetmealDishMapper setmealDishMapper;
    @Autowired
    CategoryMapper categoryMapper;
    @Autowired
    SetmealMapper setmealMapper;

    /**
     * 新增菜品
     *
     * @param dishDTO
     */
    @Override
    public void insertWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);

        dish.setStatus(StatusConstant.DISABLE);

        dishMapper.insert(dish);

        Long dishId = dish.getId();

        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(dishFlavor -> dishFlavor.setDishId(dishId));
            dishFlavorMapper.insertFlavor(flavors);
        }

    }

    /**
     * 分页查询菜品
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());

        Dish dish = new Dish();
        BeanUtils.copyProperties(dishPageQueryDTO, dish);
        if (dishPageQueryDTO.getCategoryId() != null) {
            dish.setCategoryId(Long.valueOf(dishPageQueryDTO.getCategoryId()));
        }


        Page<DishVO> pageResult = dishMapper.pageQuery(dish);

        return new PageResult(pageResult.getTotal(), pageResult.getResult());
    }

    /**
     * 批量删除菜品
     *
     * @param ids
     */
    @Override
    public void deleteByIds(List<Long> ids) {
        //先判断ids有没有数据
        if (ids.size() == 0 || ids == null) {
            return;
        }
        //判断 是否起售
        int countEnable = dishMapper.countEnableByIds(ids);
        if (countEnable > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }
        //判断 id是否被关联
        int countSetmealDish = setmealDishMapper.countByDishIds(ids);
        if (countSetmealDish > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //批量删除
        dishMapper.deleteByIds(ids);

        //批量删除口味


        dishFlavorMapper.deleteByDishIds(ids);
    }

    /**
     * 根据id查询菜品
     *
     * @param id
     * @return
     */
    @Override
    public DishVO getById(Long id) {
        Dish dish = dishMapper.getById(id);

        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);

        List<DishFlavor> flavors = dishFlavorMapper.getByDishId(id);

        dishVO.setFlavors(flavors);

        return dishVO;
    }

    /**
     * 修改菜品
     *
     * @param dishDTO
     */
    @Override
    public void update(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);

        dishMapper.update(dish);

        List<Long> ids = new ArrayList<>();
        ids.add(dishDTO.getId());
        dishFlavorMapper.deleteByDishIds(ids);

        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors == null || flavors.size() == 0) {
            return;
        }
        flavors.forEach(dishFlavor -> dishFlavor.setDishId(dishDTO.getId()));

        dishFlavorMapper.insertFlavor(flavors);

    }

    /**
     * 启用、禁用菜品
     *
     * @param status
     * @param id
     */
    @Override
    public void startOrStop(Integer status, Long id) {

        //根据 菜品id 获取 所有套餐的状态
        List<Integer> setmealStatus = setmealMapper.selectStatusByDishId(id);
        //根据 菜品id 获取 所有分类的状态
        List<Integer> categoryStatus = categoryMapper.selectStatusByDishId(id);

        //获取到所需状态后 开始判断
        //---------------------------------
        //如果不在分类 并且 不在套餐中 可以启用|禁用
        if ((setmealStatus.isEmpty() && categoryStatus.isEmpty())) {
            Dish dish = dishMapper.getById(id);
            dish.setStatus(status);
            dishMapper.update(dish);
            return;
        }

        if (status == StatusConstant.DISABLE) {
            //套餐里不能有停售的菜品
            ArrayList<Long> ids = new ArrayList<>();
            ids.add(id);
            Integer count = setmealDishMapper.countByDishIds(ids);
            if (count > 0) {
                throw new BaseException(MessageConstant.DISH_BY_SETMEAL_STATUS_DISABLE);
            }
        }

        if (status == StatusConstant.ENABLE) {
            //分类是启用的状态
            categoryStatus.forEach(cs -> {
                if (cs != StatusConstant.ENABLE) {
                    throw new BaseException(MessageConstant.CATEGORY_STATUS);
                }
            });
        }
        //根据ID修改菜品
        Dish dish = dishMapper.getById(id);
        dish.setStatus(status);
        dishMapper.update(dish);

        //如果在分类和套餐中 根据状态判断 是否可以 启用|禁用

        //status == 1 并且 所有分类的状态 == 1  并且 所有套餐的状态 == 1 才能启用
        //status == 0 并且 所有分类的状态 == 0  并且 所有套餐的状态 == 0 才能禁用
        //状态相同，才能更改
//        categoryStatus.forEach(cs -> {
//            if (cs != status) {
//                throw new BaseException(MessageConstant.DIFFERENT_STATUS);
//            }
//        });
//        setmealStatus.forEach(ss -> {
//            if (ss != status) {
//                throw new BaseException(MessageConstant.DIFFERENT_STATUS);
//            }
//        });


//        //根据ID修改菜品
//        Dish dish = dishMapper.getById(id);
//        dish.setStatus(status);
//        dishMapper.update(dish);


//        setmealStatus.forEach(status1 -> {
//            if (status1 == StatusConstant.ENABLE) {
//                log.info("1111");
//            }
//        });
//
//
//        categoryStatus.forEach(c -> {
//            if (c == StatusConstant.ENABLE) {
//                log.info(c + "abc");
//            } else {
//                log.info("没有");
//            }
//        });

//        //status =1 要启用
//        //那就看套餐的状态
//        //套餐禁用  那菜品就不能启用  |  套餐启用  那菜品就能启用
//        if (status==StatusConstant.ENABLE){
//           Integer setmealStatus =  setmealDishMapper.getSetmealStatusByDishId(id);
//           if (setmealStatus==StatusConstant.DISABLE){
//               throw new BaseException(MessageConstant.SETMEAL_ENABLE_FAILED);
//           }
//        }
//        //status =0 要禁用
//        //如果不在套餐里，就能禁用 | 如果在套餐里 所有套餐状态禁用 才能禁用
//        if (status==StatusConstant.DISABLE){
//
//        }


//        //根据ID修改菜品
//        Dish dish = dishMapper.getById(id);
//        dish.setStatus(status);
//        dishMapper.update(dish);
    }

    /**
     * 根据分类id查询菜品
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<DishVO> getByCategoryId(Long categoryId) {
        List<DishVO> list = categoryMapper.selectByCategoryId(categoryId);

        return list;
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
